package cloud.tianai.ram.policy.server.condition.impl;

import cloud.tianai.ram.policy.common.exception.ConditionHandlerNotFoundException;
import cloud.tianai.ram.policy.common.handler.ConditionHandler;
import cloud.tianai.ram.policy.common.model.dto.Match;
import cloud.tianai.ram.policy.common.model.dto.Action;
import cloud.tianai.ram.policy.common.model.dto.Condition;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.core.annotation.Order;

import java.util.List;

/**
 * @Author: 天爱有情
 * @date 2022/3/23 16:40
 * @Description 可以从spring中获取 ConditionHandler
 */
@Order(30)
public class SpringConditionHandlerManager extends DefaultConditionHandlerManager {


    private BeanFactory beanFactory;
    private boolean initialized = false;

    public SpringConditionHandlerManager(BeanFactory beanFactory) {
        this.beanFactory = beanFactory;
    }

    @Override
    public Match match(List<Condition> conditionList, Action action) throws ConditionHandlerNotFoundException {
        if (!initialized) {
            init();
            initialized = true;
        }
        return super.match(conditionList, action);
    }

    private void init() {
        String[] beanNames = ((ConfigurableListableBeanFactory) beanFactory).getBeanNamesForType(ConditionHandler.class);
        for (String beanName : beanNames) {
            addConditionHandler((ConditionHandler) beanFactory.getBean(beanName));
        }
    }
}
